/*
 * Copyright (C), 2002-2017, 南京苏宁软件技术有限公司
 * FileName: MainPushAreaTaskController.java
 * Author:   10070706
 * Date:     2017年1月18日 下午2:35:52
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.sawp.in.controller.task;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.reflect.TypeToken;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.constants.MainPushErrorConstants;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.in.controller.DjBaseController;
import com.suning.sawp.in.controller.MyGsonView;
import com.suning.sawp.intf.mainpushnew.AreaTaskService;
import com.suning.sawp.service.util.GsonUtils;
import com.suning.sawp.vo.mainpushnew.AreaTaskDetailVo;
import com.suning.sawp.vo.mainpushnew.AreaTaskModelDetailVo;
import com.suning.sawp.vo.mainpushnew.AreaTaskStoreDetailVo;
import com.suning.sawp.vo.mainpushnew.AreaTaskVo;

/**
 * 〈主推大区任务Controller〉<br>
 *
 * @author 10070706
 */
@RequestMapping("/adminPage/task/area")
@Controller
public class MainPushAreaTaskController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    @Autowired
    private AreaTaskService areaTaskService;

    @RequestMapping("queryAreaTaskList.do")
    public MyGsonView queryAreaTaskList(HttpServletRequest req, String taskTopic, String month, Integer pageNo,
            Integer pageSize) {
        String userId = req.getRemoteUser();
        LOGGER.info("用户{},查询大区主推任务列表，请求参数:任务主题[{}],任务时间[{}],页码[{}],页大小[{}]", userId, taskTopic, month, pageNo,
                pageSize);

        ReturnMsg<QueryResult<AreaTaskVo>> ret = new ReturnMsg<QueryResult<AreaTaskVo>>();
        try {
            String disCode5 = areaTaskService.query5DisCodeByUserId(userId);
            LOGGER.info("用户:{},对应的5位大区编码为:{}", userId, disCode5);
            QueryResult<AreaTaskVo> result = areaTaskService.queryAreaTaskInfo(disCode5, taskTopic, month, pageNo,
                    pageSize);
            ret.setData(result);
        } catch (Exception e) {
            LOGGER.error("查询大区列表异常:", e);
            ret.setError(MainPushErrorConstants.TASK_ERR_999, e.getMessage());
        }

        return setGsonView(ret);
    }

    @RequestMapping("exportAreaTaskCompleteInfo.do")
    public void exportAreaTaskCompleteInfo(String areaTaskIds, HttpServletRequest req, HttpServletResponse response) {
        String userId = req.getRemoteUser();
        LOGGER.info("用户{},导出大区任务完成情况，导出任务id为[{}]", userId, areaTaskIds);

        if (StringUtils.isEmpty(areaTaskIds)) {
            return;
        }

        String[] strIds;
        if (areaTaskIds.endsWith(",")) {
            strIds = StringUtils.substring(areaTaskIds, 0, areaTaskIds.length() - 1).split(",");
        } else {
            strIds = areaTaskIds.split(",");
        }

        Long[] longIds = new Long[strIds.length];
        for (int i = 0; i < strIds.length; i++) {
            // 转化id为Long型的，调用后面的service方法
            longIds[i] = Long.parseLong(strIds[i]);
        }

        XSSFWorkbook wb = areaTaskService.queryAreaSaleTaskCondition(longIds);
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String("大区主推任务完成情况.xlsx".getBytes("UTF-8"), "ISO8859-1"));
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            LOGGER.error("导出大区完成情况异常:", e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e1) {
                    LOGGER.error("导出大区完成情况异常:", e1);
                }
            }
        }
    }

    /**
     * 
     * 功能描述:查询大区详情页面<br>
     * 
     * @param areaTaskId
     * @return
     */
    @RequestMapping("queryAreaTaskDetailInfo.do")
    public MyGsonView queryAreaTaskDetailInfo(Long areaTaskId) {
        ReturnMsg<AreaTaskDetailVo> ret = new ReturnMsg<AreaTaskDetailVo>();
        try {
            AreaTaskDetailVo areaTaskDetail = areaTaskService.queryAreaTaskDetailInfo(areaTaskId);
            ret.setData(areaTaskDetail);
        } catch (Exception e) {
            LOGGER.error("查询大区主推任务详情异常:", e);
            ret.setError(MainPushErrorConstants.TASK_ERR_999, e.getMessage());
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: 大区任务对应款数列表<br>
     * 
     * @param areaTaskId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("queryAreaTaskModelDetail.do")
    public MyGsonView queryAreaTaskModelDetail(Long areaTaskId, Integer pageNo, Integer pageSize) {
        ReturnMsg<QueryResult<AreaTaskModelDetailVo>> ret = new ReturnMsg<QueryResult<AreaTaskModelDetailVo>>();
        try {
            QueryResult<AreaTaskModelDetailVo> areaTaskModelDetail = areaTaskService
                    .queryAreaTaskModelDetail(areaTaskId, pageNo, pageSize);
            ret.setData(areaTaskModelDetail);
        } catch (Exception e) {
            LOGGER.error("查询大区主推任务详情异常:", e);
            ret.setError(MainPushErrorConstants.TASK_ERR_999, e.getMessage());
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: 模板下载<br>
     * 
     * @param areaTaskId
     * @param response
     */
    @RequestMapping("exportAreaTaskDistInfo.do")
    public void exportAreaTaskDistInfo(Long areaTaskId, HttpServletResponse response) {
        XSSFWorkbook wb = areaTaskService.exportAreaTaskInfo(areaTaskId);
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String("大区主推任务模板.xlsx".getBytes("UTF-8"), "ISO8859-1"));
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            LOGGER.error("导出大区分配模板异常:", e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e1) {
                    LOGGER.error("导出大区分配模板异常:", e1);
                }
            }
        }
    }

    /**
     * 
     * 功能描述: 查询大区任务分配详情<br>
     * 
     * @param areaTaskId
     * @param modelId
     * @return
     */
    @RequestMapping("queryAreaTaskDistributeDetail.do")
    public MyGsonView queryAreaTaskDistributeDetail(Long areaTaskId, Long modelId) {
        ReturnMsg<List<AreaTaskStoreDetailVo>> ret = new ReturnMsg<List<AreaTaskStoreDetailVo>>();
        try {
            List<AreaTaskStoreDetailVo> allStore = areaTaskService.queryAreaTaskDistributeDetail(areaTaskId, modelId);
            ret.setData(allStore);
        } catch (Exception e) {
            LOGGER.error("查询大区款数分配详情异常:", e);
            ret.setError(MainPushErrorConstants.TASK_ERR_999, e.getMessage());
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: 页面分配门店数量<br>
     * 
     * @param areaTaskId
     * @param distInfoJson
     * @return
     */
    @RequestMapping("page2DistributeStoreNum.do")
    public MyGsonView page2DistributeStoreNum(Long areaTaskId, String distInfoJson) {
        LOGGER.info("页面分配大区任务至门店，大区任务id:{}，分配情况:{}", areaTaskId, distInfoJson);
        ReturnMsg<String> ret = new ReturnMsg<String>();
        try {
            TypeToken<List<AreaTaskStoreDetailVo>> type = new TypeToken<List<AreaTaskStoreDetailVo>>() {
            };
            List<AreaTaskStoreDetailVo> storeModelModify = GsonUtils.fromJson(distInfoJson, type);
            areaTaskService.modifyStoreTargetNum(areaTaskId, storeModelModify, Boolean.TRUE);
        } catch (Exception e) {
            LOGGER.error("大区页面分配数量至门店异常:", e);
            ret.setError(MainPushErrorConstants.TASK_ERR_999, e.getMessage());
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: 导入分配excel<br>
     * 
     * @param file
     * @param taskNo
     * @return
     */
    @RequestMapping("importStoreDistributeInfo.do")
    @ResponseBody
    public MyGsonView importStoreDistributeInfo(@RequestParam(value = "upfile", required = true) MultipartFile file,
            Long areaTaskId) {
        ReturnMsg<String> ret = new ReturnMsg<String>();
        try {
            areaTaskService.importAreaTaskDistribute(file, areaTaskId);
        } catch (Exception e) {
            LOGGER.error("大区导入分配数量至门店异常:", e);
            ret.setError(MainPushErrorConstants.TASK_ERR_999, e.getMessage());
        }
        return setGsonView(ret);
    }
}
